<template>
  <div class="p-2">
    <!-- 规则引擎 - 规则管理页面 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input
            v-model="queryParams.ruleName"
            placeholder="请输入规则名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="规则状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="规则状态" clearable style="width: 150px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="queryParams.ruleType" placeholder="规则类型" clearable style="width: 150px">
            <el-option label="设备规则" value="device" />
            <el-option label="数据规则" value="data" />
            <el-option label="告警规则" value="alarm" />
            <el-option label="场景规则" value="scene" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="10" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalRules }}</div>
            <div class="stat-label">总规则数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value active">{{ statistics.activeRules }}</div>
            <div class="stat-label">启用规则</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value triggered">{{ statistics.triggeredToday }}</div>
            <div class="stat-label">今日触发</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value error">{{ statistics.errorRules }}</div>
            <div class="stat-label">异常规则</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增规则</el-button>
          <el-button type="success" plain icon="Upload" @click="handleImport">导入规则</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport">导出规则</el-button>
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
        </div>
        <div class="toolbar-right">
          <el-button type="info" plain icon="Refresh" @click="handleRefresh">刷新</el-button>
          <el-button type="primary" plain icon="Setting" @click="handleSettings">规则设置</el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="ruleList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则ID" prop="ruleId" width="100" align="center" />
        <el-table-column label="规则名称" prop="ruleName" width="200" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.ruleName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="规则类型" prop="ruleType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getRuleTypeTagType(scope.row.ruleType)">{{ getRuleTypeText(scope.row.ruleType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="触发条件" prop="condition" width="200" show-overflow-tooltip />
        <el-table-column label="执行动作" prop="action" width="150" show-overflow-tooltip />
        <el-table-column label="优先级" prop="priority" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)">{{ getPriorityText(scope.row.priority) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="触发次数" prop="triggerCount" width="100" align="center" />
        <el-table-column label="最后触发" prop="lastTriggerTime" width="160" align="center" />
        <el-table-column label="创建时间" prop="createTime" width="160" align="center" />
        <el-table-column label="操作" width="340" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" plain size="small" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" plain size="small" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="warning" plain size="small" icon="CopyDocument" @click="handleCopy(scope.row)">复制</el-button>
            <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑规则对话框 -->
    <RuleFormDialog
      v-model:visible="dialog.visible"
      :title="dialog.title"
      :form-data="form"
      @submit="handleSubmit"
    />

    <!-- 规则详情对话框 -->
    <RuleDetailDialog
      v-model:visible="detailDialog.visible"
      :detail-data="detailData"
      :execution-history="executionHistory"
      @edit="handleEditFromDetail"
    />

    <!-- 规则设置对话框 -->
    <RuleSettingsDialog
      v-model:visible="settingsDialog.visible"
      :rule-data="settingsData"
      @save="handleSaveSettings"
    />
  </div>
</template>

<script setup name="RuleManage" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RuleFormDialog from './components/RuleFormDialog.vue'
import RuleDetailDialog from './components/RuleDetailDialog.vue'
import RuleSettingsDialog from './components/RuleSettingsDialog.vue'
import { Search, Refresh, Plus, Upload, Download, Delete, View, Edit, CopyDocument, Setting } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const multipleSelection = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ruleName: '',
  status: '',
  ruleType: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  totalRules: 156,
  activeRules: 128,
  triggeredToday: 2341,
  errorRules: 3
})

// 规则列表 - 完整数据源
const allRuleList = ref([
  // 水位监测规则
  {
    ruleId: 'R001',
    ruleName: '库水位超汛限告警',
    ruleType: 'alarm',
    condition: '库水位 >= 汛限水位',
    action: '发送紧急告警通知',
    priority: 'high',
    status: 1,
    triggerCount: 23,
    lastTriggerTime: '2024-01-15 14:30:25',
    createTime: '2024-01-10 09:15:30',
    description: '当库水位达到或超过汛限水位时立即告警'
  },
  {
    ruleId: 'R002',
    ruleName: '水位异常波动检测',
    ruleType: 'alarm',
    condition: '库水位变化率 > 0.5m/h',
    action: '发送异常告警',
    priority: 'high',
    status: 1,
    triggerCount: 12,
    lastTriggerTime: '2024-01-15 13:45:12',
    createTime: '2024-01-08 16:20:45',
    description: '检测水位异常快速变化情况'
  },
  {
    ruleId: 'R003',
    ruleName: '死水位预警',
    ruleType: 'alarm',
    condition: '库水位 <= 死水位 + 2m',
    action: '发送预警通知',
    priority: 'medium',
    status: 1,
    triggerCount: 8,
    lastTriggerTime: '2024-01-14 11:20:08',
    createTime: '2024-01-05 14:35:20',
    description: '水位接近死水位时预警'
  },
  // 流量监测规则
  {
    ruleId: 'R004',
    ruleName: '入库流量异常告警',
    ruleType: 'alarm',
    condition: '入库流量 > 5000m³/s',
    action: '启动防洪预案',
    priority: 'high',
    status: 1,
    triggerCount: 15,
    lastTriggerTime: '2024-01-15 18:00:00',
    createTime: '2024-01-12 10:45:15',
    description: '大流量入库时启动防洪措施'
  },
  {
    ruleId: 'R005',
    ruleName: '出库流量控制',
    ruleType: 'device',
    condition: '出库流量 > 设定值',
    action: '调节闸门开度',
    priority: 'medium',
    status: 1,
    triggerCount: 156,
    lastTriggerTime: '2024-01-15 12:15:30',
    createTime: '2024-01-09 08:30:45',
    description: '自动调节出库流量'
  },
  {
    ruleId: 'R006',
    ruleName: '泄洪流量监控',
    ruleType: 'data',
    condition: '泄洪流量 > 0',
    action: '记录泄洪数据',
    priority: 'high',
    status: 1,
    triggerCount: 45,
    lastTriggerTime: '2024-01-13 09:30:15',
    createTime: '2024-01-07 11:20:30',
    description: '监控和记录泄洪情况'
  },
  // 水质监测规则
  {
    ruleId: 'R007',
    ruleName: 'pH值异常告警',
    ruleType: 'alarm',
    condition: 'pH值 < 6.5 OR pH值 > 8.5',
    action: '发送水质告警',
    priority: 'medium',
    status: 1,
    triggerCount: 32,
    lastTriggerTime: '2024-01-14 22:15:45',
    createTime: '2024-01-06 14:45:20',
    description: '监控水质pH值异常'
  },
  {
    ruleId: 'R008',
    ruleName: '溶解氧过低告警',
    ruleType: 'alarm',
    condition: '溶解氧 < 5mg/L',
    action: '启动增氧设备',
    priority: 'medium',
    status: 1,
    triggerCount: 28,
    lastTriggerTime: '2024-01-15 08:20:30',
    createTime: '2024-01-11 13:25:15',
    description: '溶解氧不足时自动增氧'
  },
  {
    ruleId: 'R009',
    ruleName: '浊度超标检测',
    ruleType: 'alarm',
    condition: '浊度 > 20NTU',
    action: '发送水质异常通知',
    priority: 'low',
    status: 1,
    triggerCount: 19,
    lastTriggerTime: '2024-01-14 16:45:20',
    createTime: '2024-01-09 10:30:45',
    description: '检测水体浊度异常'
  },
  {
    ruleId: 'R010',
    ruleName: 'COD超标告警',
    ruleType: 'alarm',
    condition: 'COD > 40mg/L',
    action: '发送污染告警',
    priority: 'high',
    status: 1,
    triggerCount: 7,
    lastTriggerTime: '2024-01-13 14:20:15',
    createTime: '2024-01-08 09:15:30',
    description: '化学需氧量超标告警'
  },
  // 气象监测规则
  {
    ruleId: 'R011',
    ruleName: '暴雨预警',
    ruleType: 'alarm',
    condition: '降雨强度 > 50mm/h',
    action: '启动防汛预案',
    priority: 'high',
    status: 1,
    triggerCount: 6,
    lastTriggerTime: '2024-01-12 20:30:45',
    createTime: '2024-01-05 15:20:30',
    description: '强降雨时启动防汛措施'
  },
  {
    ruleId: 'R012',
    ruleName: '大风告警',
    ruleType: 'alarm',
    condition: '风速 > 17m/s',
    action: '发送大风告警',
    priority: 'medium',
    status: 1,
    triggerCount: 11,
    lastTriggerTime: '2024-01-14 18:15:20',
    createTime: '2024-01-07 12:45:15',
    description: '大风天气安全告警'
  },
  {
    ruleId: 'R013',
    ruleName: '气温异常监测',
    ruleType: 'data',
    condition: '气温 < -10°C OR 气温 > 45°C',
    action: '记录极端天气',
    priority: 'low',
    status: 1,
    triggerCount: 3,
    lastTriggerTime: '2024-01-10 06:30:15',
    createTime: '2024-01-06 08:20:45',
    description: '记录极端气温情况'
  },
  // 大坝安全监测规则
  {
    ruleId: 'R014',
    ruleName: '大坝位移告警',
    ruleType: 'alarm',
    condition: '水平位移 > 5mm',
    action: '发送结构安全告警',
    priority: 'high',
    status: 1,
    triggerCount: 2,
    lastTriggerTime: '2024-01-11 15:45:30',
    createTime: '2024-01-04 11:30:20',
    description: '大坝结构位移异常告警'
  },
  {
    ruleId: 'R015',
    ruleName: '渗流量异常检测',
    ruleType: 'alarm',
    condition: '渗流量 > 正常值 * 1.5',
    action: '启动安全检查',
    priority: 'high',
    status: 1,
    triggerCount: 4,
    lastTriggerTime: '2024-01-13 11:20:45',
    createTime: '2024-01-05 09:15:30',
    description: '大坝渗流异常检测'
  },
  {
    ruleId: 'R016',
    ruleName: '扬压力监控',
    ruleType: 'data',
    condition: '扬压力 > 设计值',
    action: '记录压力数据',
    priority: 'medium',
    status: 1,
    triggerCount: 18,
    lastTriggerTime: '2024-01-15 10:30:20',
    createTime: '2024-01-08 14:45:15',
    description: '监控大坝扬压力变化'
  },
  // 设备运行监测规则
  {
    ruleId: 'R017',
    ruleName: '发电机组异常告警',
    ruleType: 'alarm',
    condition: '发电功率 < 额定功率 * 0.8 AND 设备状态 = 运行',
    action: '发送设备故障告警',
    priority: 'high',
    status: 1,
    triggerCount: 9,
    lastTriggerTime: '2024-01-14 09:15:30',
    createTime: '2024-01-06 16:20:45',
    description: '发电机组运行异常检测'
  },
  {
    ruleId: 'R018',
    ruleName: '闸门开度控制',
    ruleType: 'device',
    condition: '库水位 > 正常水位 AND 闸门开度 < 50%',
    action: '自动调节闸门开度',
    priority: 'medium',
    status: 1,
    triggerCount: 67,
    lastTriggerTime: '2024-01-15 16:45:20',
    createTime: '2024-01-09 13:30:15',
    description: '根据水位自动调节闸门'
  },
  {
    ruleId: 'R019',
    ruleName: '泵站运行监控',
    ruleType: 'device',
    condition: '泵站流量 < 设定值 * 0.9',
    action: '检查泵站状态',
    priority: 'medium',
    status: 1,
    triggerCount: 34,
    lastTriggerTime: '2024-01-15 14:20:15',
    createTime: '2024-01-10 11:45:30',
    description: '泵站运行效率监控'
  },
  {
    ruleId: 'R020',
    ruleName: '设备温度过高告警',
    ruleType: 'alarm',
    condition: '设备温度 > 80°C',
    action: '启动冷却系统',
    priority: 'high',
    status: 1,
    triggerCount: 21,
    lastTriggerTime: '2024-01-14 13:30:45',
    createTime: '2024-01-07 10:15:20',
    description: '设备过热保护'
  },
  // 综合监控规则
  {
    ruleId: 'R021',
    ruleName: '夜间安全巡检',
    ruleType: 'schedule',
    condition: '时间 = 22:00',
    action: '启动自动巡检程序',
    priority: 'low',
    status: 1,
    triggerCount: 30,
    lastTriggerTime: '2024-01-14 22:00:00',
    createTime: '2024-01-05 17:30:15',
    description: '定时夜间安全巡检'
  },
  {
    ruleId: 'R022',
    ruleName: '数据备份规则',
    ruleType: 'schedule',
    condition: '时间 = 02:00',
    action: '执行数据备份',
    priority: 'low',
    status: 1,
    triggerCount: 15,
    lastTriggerTime: '2024-01-15 02:00:00',
    createTime: '2024-01-08 18:45:30',
    description: '定时数据备份任务'
  },
  {
    ruleId: 'R023',
    ruleName: '系统健康检查',
    ruleType: 'schedule',
    condition: '时间 = 06:00',
    action: '执行系统诊断',
    priority: 'medium',
    status: 1,
    triggerCount: 15,
    lastTriggerTime: '2024-01-15 06:00:00',
    createTime: '2024-01-09 19:20:15',
    description: '定时系统健康检查'
  },
  {
    ruleId: 'R024',
    ruleName: '能耗统计规则',
    ruleType: 'data',
    condition: '发电功率 > 0',
    action: '记录发电量数据',
    priority: 'low',
    status: 1,
    triggerCount: 2341,
    lastTriggerTime: '2024-01-15 17:30:45',
    createTime: '2024-01-06 12:15:30',
    description: '统计发电量和能耗'
  },
  {
    ruleId: 'R025',
    ruleName: '水库调度优化',
    ruleType: 'device',
    condition: '入库流量 > 出库流量 * 2 AND 库水位 < 正常水位',
    action: '优化调度方案',
    priority: 'medium',
    status: 1,
    triggerCount: 89,
    lastTriggerTime: '2024-01-15 15:20:30',
    createTime: '2024-01-10 14:30:45',
    description: '智能水库调度优化'
  },
  // 环境监测规则
  {
    ruleId: 'R026',
    ruleName: '水温异常监测',
    ruleType: 'alarm',
    condition: '水温 < 4°C OR 水温 > 35°C',
    action: '发送水温异常告警',
    priority: 'medium',
    status: 1,
    triggerCount: 14,
    lastTriggerTime: '2024-01-13 12:45:20',
    createTime: '2024-01-07 15:30:15',
    description: '监测水温异常变化'
  },
  {
    ruleId: 'R027',
    ruleName: '电导率异常检测',
    ruleType: 'alarm',
    condition: '电导率 > 1500μS/cm',
    action: '发送水质告警',
    priority: 'medium',
    status: 1,
    triggerCount: 8,
    lastTriggerTime: '2024-01-12 14:20:15',
    createTime: '2024-01-08 11:45:30',
    description: '电导率异常检测'
  },
  {
    ruleId: 'R028',
    ruleName: '氨氮超标告警',
    ruleType: 'alarm',
    condition: '氨氮 > 2.0mg/L',
    action: '启动水质处理',
    priority: 'high',
    status: 1,
    triggerCount: 5,
    lastTriggerTime: '2024-01-11 16:30:45',
    createTime: '2024-01-09 13:20:15',
    description: '氨氮含量超标处理'
  },
  {
    ruleId: 'R029',
    ruleName: '总磷监控规则',
    ruleType: 'data',
    condition: '总磷 > 0.1mg/L',
    action: '记录富营养化风险',
    priority: 'medium',
    status: 1,
    triggerCount: 12,
    lastTriggerTime: '2024-01-14 10:15:30',
    createTime: '2024-01-10 09:45:20',
    description: '监控水体富营养化风险'
  },
  {
    ruleId: 'R030',
    ruleName: '蒸发量统计',
    ruleType: 'data',
    condition: '蒸发量 > 0',
    action: '累计蒸发量数据',
    priority: 'low',
    status: 1,
    triggerCount: 365,
    lastTriggerTime: '2024-01-15 18:00:00',
    createTime: '2024-01-05 08:30:15',
    description: '统计水库蒸发量'
  },
  // 安全防护规则
  {
    ruleId: 'R031',
    ruleName: '非授权访问告警',
    ruleType: 'alarm',
    condition: '访问时间 NOT IN 工作时间 AND 访问权限 = 未授权',
    action: '发送安全告警',
    priority: 'high',
    status: 1,
    triggerCount: 3,
    lastTriggerTime: '2024-01-13 23:45:20',
    createTime: '2024-01-06 17:20:30',
    description: '非工作时间未授权访问告警'
  },
  {
    ruleId: 'R032',
    ruleName: '设备离线检测',
    ruleType: 'alarm',
    condition: '设备状态 = 离线 AND 离线时长 > 30分钟',
    action: '发送设备离线告警',
    priority: 'medium',
    status: 1,
    triggerCount: 27,
    lastTriggerTime: '2024-01-15 11:30:15',
    createTime: '2024-01-08 16:45:30',
    description: '关键设备离线告警'
  },
  {
    ruleId: 'R033',
    ruleName: '通信故障检测',
    ruleType: 'alarm',
    condition: '通信延迟 > 5秒 OR 数据丢包率 > 10%',
    action: '切换备用通信链路',
    priority: 'high',
    status: 1,
    triggerCount: 16,
    lastTriggerTime: '2024-01-14 15:20:45',
    createTime: '2024-01-09 12:30:20',
    description: '通信链路故障自动切换'
  },
  {
    ruleId: 'R034',
    ruleName: '数据异常清洗',
    ruleType: 'data',
    condition: '数据值 = NULL OR 数据值 < 0 OR 数据值 > 上限值',
    action: '标记并清洗异常数据',
    priority: 'low',
    status: 1,
    triggerCount: 156,
    lastTriggerTime: '2024-01-15 17:45:30',
    createTime: '2024-01-07 14:20:15',
    description: '自动清洗异常数据'
  },
  {
    ruleId: 'R035',
    ruleName: '预测性维护',
    ruleType: 'schedule',
    condition: '设备运行时长 > 8760小时',
    action: '生成维护计划',
    priority: 'medium',
    status: 1,
    triggerCount: 8,
    lastTriggerTime: '2024-01-12 09:15:30',
    createTime: '2024-01-05 13:45:20',
    description: '基于运行时长的预测性维护'
  }
])

// 显示的规则列表（过滤后的）
const ruleList = ref([])

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false
})

const settingsDialog = reactive({
  visible: false
})

// 表单数据
const form = reactive({
  ruleId: '',
  ruleName: '',
  ruleType: '',
  priority: 'medium',
  status: 1,
  description: '',
  condition: '',
  action: ''
})

// 详情数据
const detailData = reactive({})

// 执行历史
const executionHistory = ref([
  {
    executeTime: '2024-01-15 14:30:25',
    status: 'success',
    result: '告警通知发送成功',
    duration: 125
  },
  {
    executeTime: '2024-01-15 13:45:12',
    status: 'success',
    result: '设备状态更新完成',
    duration: 89
  },
  {
    executeTime: '2024-01-15 12:15:30',
    status: 'failed',
    result: '网络连接超时',
    duration: 5000
  }
])

// 设置数据
const settingsData = reactive({
  engineEnabled: true,
  maxConcurrency: 100,
  executeTimeout: 30,
  logLevel: 'info',
  retryCount: 3
})



// 获取规则类型标签类型
const getRuleTypeTagType = (type: string) => {
  const typeMap = {
    device: 'primary',
    data: 'success',
    alarm: 'danger',
    scene: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取规则类型文本
const getRuleTypeText = (type: string) => {
  const typeMap = {
    device: '设备规则',
    data: '数据规则',
    alarm: '告警规则',
    scene: '场景规则'
  }
  return typeMap[type] || type
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

// 格式化JSON
const formatJSON = (jsonStr: string) => {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

// 过滤规则列表
const filterRuleList = () => {
  let filtered = [...allRuleList.value]
  
  // 按规则名称过滤
  if (queryParams.ruleName) {
    filtered = filtered.filter(rule => 
      rule.ruleName.toLowerCase().includes(queryParams.ruleName.toLowerCase())
    )
  }
  
  // 按状态过滤
  if (queryParams.status !== '') {
    filtered = filtered.filter(rule => rule.status === Number(queryParams.status))
  }
  
  // 按规则类型过滤
  if (queryParams.ruleType) {
    filtered = filtered.filter(rule => rule.ruleType === queryParams.ruleType)
  }
  
  // 按创建时间范围过滤
  if (queryParams.dateRange && queryParams.dateRange.length === 2) {
    const [startDate, endDate] = queryParams.dateRange
    filtered = filtered.filter(rule => {
      const createDate = rule.createTime.split(' ')[0]
      return createDate >= startDate && createDate <= endDate
    })
  }
  
  // 分页处理
  const start = (queryParams.pageNum - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  
  total.value = filtered.length
  ruleList.value = filtered.slice(start, end)
  
  // 更新统计数据
  updateStatistics(filtered)
}

// 更新统计数据
const updateStatistics = (rules = allRuleList.value) => {
  const stats = {
    total: rules.length,
    enabled: 0,
    disabled: 0,
    device: 0,
    alarm: 0,
    data: 0,
    schedule: 0,
    high: 0,
    medium: 0,
    low: 0,
    todayTrigger: 0,
    totalTrigger: 0
  }
  
  const today = new Date().toISOString().split('T')[0]
  
  rules.forEach(rule => {
    // 状态统计
    if (rule.status === 1 || rule.status === 'enabled') {
      stats.enabled++
    } else {
      stats.disabled++
    }
    
    // 类型统计
    switch (rule.ruleType) {
      case 'device':
        stats.device++
        break
      case 'alarm':
        stats.alarm++
        break
      case 'data':
        stats.data++
        break
      case 'schedule':
        stats.schedule++
        break
    }
    
    // 优先级统计
    switch (rule.priority) {
      case 'high':
        stats.high++
        break
      case 'medium':
        stats.medium++
        break
      case 'low':
        stats.low++
        break
    }
    
    // 触发次数统计
    const triggerCount = rule.triggerCount || 0
    stats.totalTrigger += triggerCount
    
    // 今日触发统计（如果最后触发时间是今天）
    if (rule.lastTriggerTime && rule.lastTriggerTime.includes(today)) {
      stats.todayTrigger += triggerCount
    }
  })
  
  // 更新统计数据
  statistics.totalRules = stats.total
  statistics.activeRules = stats.enabled
  statistics.triggeredToday = stats.todayTrigger
  statistics.errorRules = stats.disabled
}

// 查询
const handleQuery = () => {
  loading.value = true
  // 模拟API调用延迟
  setTimeout(() => {
    filterRuleList()
    loading.value = false
    ElMessage.success('查询完成')
  }, 500)
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    ruleName: '',
    status: '',
    ruleType: '',
    dateRange: []
  })
  handleQuery()
  ElMessage.info('查询条件已重置')
}

// 新增
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增规则'
  // 重置表单数据，确保是新增模式
  dialog.formData = {
    ruleId: '',
    ruleName: '',
    ruleType: '',
    priority: 'medium',
    status: 1,
    description: '',
    condition: '',
    action: '',
    executionFrequency: 'immediate',
    delayTime: 0,
    maxRetries: 3,
    triggerMode: 'realtime',
    cooldownTime: 0,
    maxTriggers: 0
  }
}

// 处理编辑规则
const handleEdit = (row: any) => {
  dialog.visible = true
  dialog.title = '编辑规则'
  // 深拷贝数据，确保编辑模式正确回显
  dialog.formData = {
    ...row,
    // 确保所有字段都有默认值
    executionFrequency: row.executionFrequency || 'immediate',
    delayTime: row.delayTime || 0,
    maxRetries: row.maxRetries || 3,
    triggerMode: row.triggerMode || 'realtime',
    cooldownTime: row.cooldownTime || 0,
    maxTriggers: row.maxTriggers || 0
  }
}

// 处理查看规则详情
const handleView = (row: any) => {
  detailDialog.visible = true
  detailData.value = { ...row }
}

// 处理复制规则
const handleCopy = (row: any) => {
  dialog.visible = true
  dialog.title = '复制规则'
  // 复制数据但清空ID，作为新增处理
  dialog.formData = {
    ...row,
    ruleId: '', // 清空ID，表示新增
    ruleName: `${row.ruleName}_副本`, // 添加副本标识
    // 确保所有字段都有默认值
    executionFrequency: row.executionFrequency || 'immediate',
    delayTime: row.delayTime || 0,
    maxRetries: row.maxRetries || 3,
    triggerMode: row.triggerMode || 'realtime',
    cooldownTime: row.cooldownTime || 0,
    maxTriggers: row.maxTriggers || 0
  }
}

// 处理表单提交
const handleSubmit = (formData: any) => {
  try {
    // 判断是否为编辑模式：检查原始表单数据是否有ruleId
    const isEditMode = dialog.formData && dialog.formData.ruleId && dialog.formData.ruleId !== ''
    
    if (isEditMode) {
      // 编辑模式：更新现有规则
      const index = allRuleList.value.findIndex(rule => rule.ruleId === dialog.formData.ruleId)
      if (index !== -1) {
        // 更新规则数据，保留原有的统计信息
        const originalRule = allRuleList.value[index]
        allRuleList.value[index] = {
          ...formData,
          ruleId: dialog.formData.ruleId, // 保持原有的ruleId
          // 保留原有的统计数据
          triggerCount: originalRule.triggerCount,
          lastTriggerTime: originalRule.lastTriggerTime,
          createTime: originalRule.createTime,
          // 更新修改时间
          updateTime: new Date().toLocaleString()
        }
        ElMessage.success('规则更新成功')
      } else {
        ElMessage.error('未找到要更新的规则')
        return
      }
    } else {
      // 新增模式：添加新规则
      const newRule = {
        ...formData,
        // 确保使用新生成的ruleId或重新生成
        ruleId: formData.ruleId || 'R' + Date.now().toString().slice(-6),
        triggerCount: 0,
        lastTriggerTime: '-',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
      allRuleList.value.unshift(newRule) // 添加到列表开头
      ElMessage.success('规则创建成功')
    }
    
    // 关闭对话框
    dialog.visible = false
    dialog.formData = {}
    
    // 刷新数据和统计
    refreshData()
    
  } catch (error) {
    console.error('提交规则时出错:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 刷新数据
const refreshData = () => {
  // 重新过滤数据
  filterRuleList()
  // 更新统计信息
  updateStatistics()
}

// 从详情页面编辑
const handleEditFromDetail = (ruleData: any) => {
  detailDialog.visible = false
  handleEdit(ruleData)
}

// 保存设置
const handleSaveSettings = (settings: any) => {
  console.log('保存设置:', settings)
  // 更新本地设置数据
  Object.assign(settingsData, settings)
  ElMessage.success('设置保存成功')
  settingsDialog.visible = false
}

// 选择变更
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  handleQuery()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  handleQuery()
}

// 组件挂载
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-value.active {
  color: #67c23a;
}

.stat-value.triggered {
  color: #409eff;
}

.stat-value.error {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.condition-code,
.action-code {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin: 10px 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
  overflow-x: auto;
}
</style>